<template>
  <div class="login">
    <header class="login_header">
      <img class="login_header_img" src="@/assets/images/logo.png" />
      <span class="login_header_title">麦房宝工作台</span>
    </header>

    <div class="login_warp">
      <div class="login_from">
        <h3 class="login_from_title">{{ timeType }}，欢迎回来~</h3>
        <!-- 手机验证码登录 -->
        <template v-if="loginType === 1">
          <code-login v-model="params" @roles="(val) => (roleList = val)" />
        </template>
        <!-- 密码登录 -->
        <template v-if="loginType === 2">
          <pwd-login ref="pwdLogin" v-model="params" @roles="(val) => (roleList = val)" />
        </template>

        <div class="login-button">
          <Button type="primary" size="large" :loading="loginIng" @click="onLogin">
            {{ loginIng ? '登录中...' : '登录' }}
          </Button>
          <p>
            <span v-if="loginType === 1" @click="changeType(2)">使用密码登录</span>
            <span v-else @click="changeType(1)">使用验证码登录</span>
            <span @click="forgetPwd()">忘记密码</span>
          </p>
        </div>
      </div>
    </div>
    <footer>
      <div class="footer">
        <p style="color: #333">Copyright © 2020 www.tospurfang.com 版权所有</p>
      </div>
    </footer>
    <!-- 忘记密码 -->
    <div v-if="setPwdVisible">
      <set-password :visible="setPwdVisible" :isUpdate="true" @close="() => (setPwdVisible = false)" />
    </div>
  </div>
</template>
<script>
  import codeLogin from './components/code-login.vue'
  import pwdLogin from './components/pwd-login.vue'
  import SetPassword from '@/layout/components/set-password.vue'
  import { beginAddRouter } from '@/router/routerSlider'
  import userMgr from '@/biz/user'

  export default {
    components: {
      codeLogin,
      pwdLogin,
      SetPassword
    },
    data() {
      return {
        timeType: '上午好',
        roleList: [],
        loginType: 2,
        params: {
          searchKey: '',
          code: '',
          password: '',
          uuid: '',
          roleId: ''
        },
        loginIng: false,
        setPwdVisible: false
      }
    },
    beforeRouteLeave(to, from, next) {
      this.loginIng = false
      next()
    },
    created() {
      this.checkTimeType()
      this.$tool.clearStorage(['isbuildFlag', 'rouList', 'buildrouList', 'buttonControl', 'menuControl'])
      document.onkeydown = (e) => {
        if (e.keyCode == 13) {
          this.onLogin()
        }
      }
      this.deletewaterMask()
    },
    methods: {
      // 忘记密码
      forgetPwd() {
        this.setPwdVisible = true
      },
      // 关闭水印
      deletewaterMask() {
        const ele = document.getElementById('watermark')
        if (ele) {
          document.body.removeChild(ele)
        }
      },
      // 登录
      onLogin() {
        console.log(this.params, '000000')
        // 校验成功
        if (this.onValidate()) {
          this.loginIng = true
          let appId = 36
          let obj = {
            loginType: this.loginType,
            searchKey: this.params.searchKey,
            roleId: this.params.roleId - 0,
            appId
          }
          if (this.loginType === 1) {
            obj.code = this.params.code
          } else {
            obj.password = this.params.password
            if (this.params.code) obj.code = this.params.code
            if (this.params.uuid) obj.uuid = this.params.uuid
          }
          this.$tool.setStorage({ appId })
          if (this.params.authId) {
            obj.authId = this.params.authId
          }

          userMgr
            .login(obj)
            .then((res) => {
              console.log(res, '登录')
              this.$dt.stats.login()
              let authId = this.params.authId ? this.params.authId : ''
              this.$tool.setStorage({ authId: JSON.stringify(authId) })
              beginAddRouter(res.userId, res.role.roleId, false, res.roleType, authId)
            })
            .catch((err) => {
              if (this.loginType == 2) {
                if (err.data && err.data >= 2) {
                  this.$refs.pwdLogin.showCode = true
                  this.$refs.pwdLogin.getImgCode()
                } else {
                  this.$refs.pwdLogin.showCode = false
                }
              }
              this.$tool.clearStorage(['appId'])
              this.loginIng = false
              throw err
            })

          // 获取菜单/按钮权限，权限不为空才可登录
          // beginAddRouter(obj.searchKey, obj.roleId, false, () => {
          //   return userMgr.login(obj).then(res => {
          //     this.$dt.stats.login()
          //   }).catch((err) => {
          //     if (this.loginType == 2) {
          //       if (err.data && err.data >= 2) {
          //         this.$refs.pwdLogin.showCode = true
          //         this.$refs.pwdLogin.getImgCode()
          //       } else {
          //         this.$refs.pwdLogin.showCode = false
          //       }
          //     }
          //     this.$tool.clearStorage(['appId'])
          //     this.loginIng = false
          //     throw err
          //   })
          // }).catch((err) => {
          //   this.$Message.error(err)
          //   this.$tool.clearStorage(['appId'])
          //   this.loginIng = false
          // })
        }
      },
      // 登录字段校验
      onValidate() {
        let { searchKey, code, roleId, password, uuid } = this.params
        if (this.loginType === 1) {
          const reg = /^1[3456789]\d{9}$/
          if (!searchKey) {
            this.$Message.warning('请输入手机号')
            return false
          }
          if (!reg.test(searchKey)) {
            this.$Message.warning('手机号码有误，请核对')
            return false
          }
          if (!code || code.length != 6) {
            this.$Message.warning('请输入6位验证码')
            return false
          }
        } else {
          const reg1 = /^[a-zA-Z0-9]{5,6}$/,
            reg2 = /^1[3456789]\d{9}$/
          if (!searchKey) {
            this.$Message.warning('请输入工号或手机号')
            return false
          }
          // if (
          //   (searchKey.length !== 5 && searchKey.length !== 6 && searchKey.length !== 11) ||
          //   ((searchKey.length === 5 || searchKey.length === 6) && !reg1.test(searchKey)) ||
          //   (searchKey.length === 11 && !reg2.test(searchKey))
          // ) {
          //   this.$Message.warning('工号或手机号有误，请核对')
          //   return false
          // }
          if (!password) {
            this.$Message.warning('请输入密码')
            return false
          }
        }
        if (!roleId) {
          this.$Message.warning('您尚未选择角色,请先选择角色')
          return false
        }
        return true
      },
      changeType(val) {
        console.log(val, 'change')
        this.loginType = val
        this.params = {
          searchKey: '',
          code: '',
          password: '',
          uuid: '',
          roleId: ''
        }
      },
      // 判断当前时间是早上 中午 下午 晚上好
      checkTimeType() {
        let now = new Date(),
          hour = now.getHours()
        if (hour < 9) {
          this.timeType = '早上好'
        } else if (hour < 12) {
          this.timeType = '上午好'
        } else if (hour < 14) {
          this.timeType = '中午好'
        } else if (hour < 17) {
          this.timeType = '下午好'
        } else {
          this.timeType = '晚上好'
        }
      }
    },
    beforeDestroy() {
      document.onkeydown = ''
    }
  }
</script>
<style lang="scss" scoped>
  .login {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: url('https://images.tospurfang.com/7fc45fd70446408cb3ec40e99ce40767.png') no-repeat;
    background-size: cover;
    background-position: center;

    .login_header {
      position: absolute;
      width: 100%;
      overflow: hidden;
      top: 3vh;
      padding-left: 100px;

      &_img {
        height: 32px;
        width: 31px;
        display: inline-block;
        margin-right: 10px;
      }

      &_title {
        vertical-align: top;
        display: inline-block;
        line-height: 32px;
        height: 32px;
        font-size: 18px;
        font-weight: 700;
      }
    }

    .login_warp {
      position: absolute;
      top: 20vh;
      width: 100%;
      min-width: 990px;
    }

    footer {
      position: absolute;
      bottom: 80px;
      left: 50%;
      transform: translateX(-50%);
      background: rgba(255, 255, 255, 0.6);
      border-radius: 15px;
      padding: 0 20px;
      height: 30px;
      line-height: 30px;
    }

    &_from {
      width: 400px;
      margin: 0 auto;

      &_title {
        font-size: 40px;
        font-weight: 700;
        margin-bottom: 60px;
        text-align: center;
      }
    }

    .login-button {
      display: flex;
      align-items: center;
      margin-top: 20px;

      > p {
        width: 40%;
        display: flex;
        justify-content: space-between;
        margin-left: 5%;

        span {
          color: #333333;
          text-decoration: underline;
          cursor: pointer;
        }
      }

      button {
        flex: 1;
      }
    }
  }
</style>
